class GameRunningsController < ApplicationController
  include ActionView::Helpers::NumberHelper
  def pre_gamepanel
    redirect_to :action=>"gamepanel", :gencode=>params[:gencode]
  end

  def futures_area
    render :action=>"futures_area", :layout=>false
  end

  def gamepanel_a
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    render :action=>"gamepanel_a", :layout=>"basic_noheader_layout"
  end

  def calculate
    @gencode = params[:id]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @players = Player.find(:all, :conditions=>["game_id=? AND player_type=? AND remain_inventory>0", @game.id, "B"], :order=>"id")
    render :action=>"calculate", :layout=>false
  end

  def calculate_share
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=? AND remain_inventory>0", game.id, "B"], :order=>"id")
    promotion_array = Array.new
    promotion_rank = Array.new
    if params[:prank]
      players.each do |p|
        promotion_array = promotion_array << p.promotion
      end
      promotion_rank = array_rank_desc(promotion_array)
      players.each_with_index do |p,i|
        sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, p.id])
        sale.action_rank = promotion_rank[i]
        sale.promotion = p.promotion
        sale.save
      end
    end

    if params[:cal]
      total_score = 0.0000
      players.each do |p|
        sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, p.id])
        sold_flag = 0
        if !params["sold_flag_#{p.id}".to_sym].empty?
          sold_flag = params["sold_flag_#{p.id}".to_sym].to_i
        end
        price_rank = players.length + 1
        if !params["price_rank_#{p.id}".to_sym].empty?
          price_rank = params["price_rank_#{p.id}".to_sym].to_i
        end
        action_flag = 0
        if !params["action_flag_#{p.id}".to_sym].empty?
          action_flag = params["action_flag_#{p.id}".to_sym].to_i
        end
        action_rank = players.length + 1
        if !params["action_rank_#{p.id}".to_sym].empty?
          action_rank = params["action_rank_#{p.id}".to_sym].to_i
        end
        score = game.game_setting.price_weight*(sold_flag*(players.length+1-price_rank)/players.length.to_f) + (1-game.game_setting.price_weight)*(action_flag*(players.length+1-action_rank)/players.length.to_f)
        total_score = total_score + score
        sale.action_rank = action_rank
        sale.score = score
        sale.save
      end
      players.each do |p|
        sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, p.id])
        sale.remain_share = sale.score/total_score
        sale.save
      end
    end

    if params[:al]
      allocate_share(game.id, 0)
      players.each do |p|
        promotion = Sale.sum(:promotion, :conditions=>["game_id=? AND year=? AND player_id=?", game.id, game.current_year, p.id])
        pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
        pb.promotion = promotion
        pb.save
      end
      redirect_to :action=>"calculate_close", :id=>params[:id]
    else
      redirect_to :action=>"calculate", :id=>params[:id]
    end
  end

  def calculate_close
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"], :order=>"id")
    players.each do |p|
      sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, p.id])
      if sale
        sale.sale_flag = 'N'
        sale.save
      end
    end
    render :action=>"calculate_close", :layout=>false
  end

  def allocate_share(game_id, count)
    game = Game.find(game_id)
    total = 0
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=? AND remain_inventory>0", game.id, "B"], :order=>"id")
    total_weight = 0.00
    remain_players = Player.find(:all, :conditions=>["game_id=? AND player_type=? AND remain_inventory>0", game.id, "B"], :order=>"id")
    remain_players.each do |rp|
      sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, rp.id])
      total_weight = total_weight + sale.remain_share
    end
    if total_weight>0
      players.each do |p|
        sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, p.id])
        sold = 0
        market_remain = game.market_remain
        player_remain = p.remain_inventory
        presold = (market_remain * sale.remain_share / total_weight).to_i
        sold = (presold/10000.0).round * 10000
        if sold>player_remain
          sold = player_remain
        end
        if sold>market_remain
          sold = market_remain
        end
        total = total + sold
        sale.quantity = sale.quantity + sold
        if sale.price>sale.random_price
          sale.price = sale.random_price
        end
        sale.cash = sale.cash + (sold * (sale.price + sale.price_added))
        sale.save

        p.remain_inventory = player_remain - sold
        p.save
      end
    end
    game.market_remain = game.market_remain - total
    game.save

    if total<=0
      
    elsif game.market_remain<=0

    else
      allocate_share(game_id, count+1)
    end
  end

  def gamepanel
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @price = ''
    p = Price.find(:first, :conditions=>["game_id=? AND year=? AND round=?", @game.id, @game.current_year, @game.current_round])
    if p
      @price = p.price
    end
    @sales = Sale.find(:all, :conditions=>["game_id=? AND year=? AND round=? AND sale_flag=?", @game.id, @game.current_year, @game.current_round, 'Y'])
    render :action=>"gamepanel", :layout=>"basic_noheader_layout"
  end

  def summary
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    @a_players = Player.find(:all, :conditions=>["game_id=? AND player_type=?",@game.id, "A"])
    @b_players = Player.find(:all, :conditions=>["game_id=? AND player_type=?",@game.id, "B"])
    render :action=>"summary", :layout=>"basic_noheader_layout"
  end

  def summary_view
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    @a_players = Player.find(:all, :conditions=>["game_id=? AND player_type=?",@game.id, "A"])
    @b_players = Player.find(:all, :conditions=>["game_id=? AND player_type=?",@game.id, "B"])
    render :action=>"summary_view", :layout=>"basic_noheader_layout"
  end  

  def random_price
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game_setting = game.game_setting
    min = params[:min].to_i
    max = params[:max].to_i
    if game_setting.rational_random=='Y'
      total_demand = game.market_remain + Contract.sum(:total_unit, :conditions=>["game_id=? AND end_year=? AND c_type=? AND open_flag=?", game.id, game.current_year, "buy", "Y"])
      total_supply = Player.sum(:remain_inventory, :conditions=>["game_id=? AND player_type=?", game.id, "B"]) + Contract.sum(:total_unit, :conditions=>["game_id=? AND end_year=? AND c_type=? AND open_flag=?", game.id, game.current_year, "sell", "Y"])
      if total_supply<1
        total_supply = 1
      end
      if total_demand.to_f/total_supply >= game_setting.high_d2s
        min = (min + ((max - min) * game_setting.min_highrange)).to_i
        max = (min + ((max - min) * game_setting.max_highrange)).to_i
      elsif total_demand.to_f/total_supply <= game_setting.low_d2s
        min = (min + ((max - min) * game_setting.min_lowrange)).to_i
        max = (min + ((max - min) * game_setting.max_lowrange)).to_i
      else
        min = (min + ((max - min) * game_setting.min_midrange)).to_i
        max = (min + ((max - min) * game_setting.max_midrange)).to_i
      end
    end
    price = rand(max-min+1) + min
    game_setting.last_price = price
    game_setting.save
    render :text=>price, :layout=>false
  end

  def random_market
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    min = (game.market_size + (game.market_size * params[:min].to_f)).to_i
    max = (game.market_size + (game.market_size * params[:max].to_f)).to_i
    market = rand(max-min+1) + min
    market = (market/100000.0).round * 100000
    render :text=>number_with_delimiter(market), :layout=>false
  end

  def lock_inventory
    gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",gencode])
    game.edit_inventory = 'N'
    game.save
    redirect_to :action=>"gamepanel", :gencode=>gencode
  end

  def unlock_inventory
    gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",gencode])
    game.edit_inventory = 'Y'
    game.save
    redirect_to :action=>"gamepanel", :gencode=>gencode
  end

  def lock_price
    gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",gencode])
    game.edit_price = 'N'
    game.save
    redirect_to :action=>"gamepanel", :gencode=>gencode
  end

  def unlock_price
    gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",gencode])
    game.edit_price = 'Y'
    game.save
    redirect_to :action=>"gamepanel", :gencode=>gencode
  end

  def mark_futures(contract_id)
    contract = Contract.find(contract_id)
    game = Game.find(contract.game_id)
    game_setting = game.game_setting
    settlement_price = nil
    if game_setting.average_price
      settlement_price = game_setting.average_price
    else
      settlement_price = (game_setting.f01_price.to_f/(1.0 + game_setting.level1_debt_rate)).round(2)
    end
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", contract.player_id, game.current_year])
    last_value = contract.current_value
    sold_price = nil
    if game.run_flag=='N'
      sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year + 1))).round(2)
    else
      sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year))).round(2)
    end
    val = nil
    if contract.c_type=='sell'
      val = (contract.unit_price - sold_price) * contract.total_unit
    else
      val = (sold_price - contract.unit_price) * contract.total_unit
    end
    #current_value = contract.initial_margin + val
    current_value = contract.current_value + val
    current_value = (current_value/10000.0).round * 10000
    if current_value <= contract.maintenance_margin
      pb.cash = pb.cash - (contract.initial_margin - current_value)
      pb.futures_revenue = pb.futures_revenue - (last_value - current_value)
      pb.futures = pb.futures + (contract.initial_margin - last_value)
      contract.current_value = contract.initial_margin
      contract.call_count = contract.call_count + (contract.initial_margin - current_value)
    else
      pb.futures = pb.futures - (last_value - current_value)
      pb.futures_revenue = pb.futures_revenue - (last_value - current_value)
      contract.current_value = current_value
    end
    contract.market_price = settlement_price
    contract.unit_price = sold_price
    contract.save
    pb.save
  end

  def force_close_futures(contract_id)
    contract = Contract.find(contract_id)
    game = Game.find(contract.game_id)
    game_setting = game.game_setting
    settlement_price = nil
    if game_setting.average_price
      settlement_price = game_setting.average_price
    else
      if game_setting.last_price
        game_setting.average_price = game_setting.last_price
        game_setting.save
        settlement_price = game_setting.average_price
      else
        settlement_price = (game_setting.f01_price.to_f/(1.0 + game_setting.level1_debt_rate)).round(2)
        game_setting.average_price = settlement_price
        game_setting.save
      end
    end
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", contract.player_id, game.current_year])
    last_value = contract.current_value
    sold_price = nil
    if game.run_flag=='N'
      sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year + 1))).round(2)
    else
      sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year))).round(2)
    end
    val = nil
    if contract.c_type=='sell'
      val = (contract.unit_price - sold_price) * contract.total_unit
    else
      val = (sold_price - contract.unit_price) * contract.total_unit
    end
    #current_value = contract.initial_margin + val
    current_value = contract.current_value + val
    current_value = (current_value/10000.0).round * 10000
    pb.cash = pb.cash + current_value
    pb.futures = pb.futures - last_value
    pb.futures_revenue = pb.futures_revenue - (last_value - current_value)
    pb.save
    contract.settlement_price = settlement_price
    contract.close_year = game.current_year
    contract.open_flag = 'N'
    contract.current_value = current_value
    contract.save

#    game_setting.total_q = game_setting.total_q + contract.total_unit
#    game_setting.total_mul = game_setting.total_mul + (settlement_price * contract.total_unit)
#    game_setting.average_price = (game_setting.total_mul.to_f / game_setting.total_q).round(2)
#    game_setting.save
  end

  def auto_futures(game_id)
    game = Game.find(game_id)
    contracts = Contract.find(:all, :conditions=>["game_id=? AND open_flag=? AND end_year=?", game_id, "Y", game.current_year])
    contracts.each do |c|
      force_close_futures(c.id)
    end
    contracts = Contract.find(:all, :conditions=>["game_id=? AND open_flag=? AND end_year>?", game_id, "Y", game.current_year])
    contracts.each do |c|
      mark_futures(c.id)
    end
  end

  def start_year
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game_setting = game.game_setting
    game.run_flag = 'Y'
    game.current_round = 0

    min_error = game.min_error
    max_error = game.max_error
    game_error = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    if game_error
      min_error = game_error.min_error
      max_error = game_error.max_error
    end
    min = (game.market_size + (game.market_size * min_error)).to_i
    max = (game.market_size + (game.market_size * max_error)).to_i
    market = rand(max-min+1) + min
    market = (market/100000.0).round * 100000

    game.market_size = market
    game.market_remain = market
    game.save

    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, 'B'])
    players.each do |p|
      level = p.level
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
      if pb
        produce = pb.onprocess_inventory_unit
        pb.inventory_unit = pb.inventory_unit + produce
        pb.inventory_cost = ((pb.inventory_cost + (produce * pb.rawmat_unitcost))/10000.0).round * 10000
        if pb.inventory_unit==0
          pb.inventory_unitcost = 0
        else
          pb.inventory_unitcost = pb.inventory_cost.to_f/pb.inventory_unit
        end

        pb.rawmat_unit = pb.rawmat_unit - produce
        pb.rawmat_cost = ((pb.rawmat_unitcost * pb.rawmat_unit)/10000.0).round * 10000

        p.remain_inventory = pb.inventory_unit
        com_produce = p.com_produce + produce
        if pb.marketing==0
          p.com_produce = com_produce
          if level==0
            if com_produce>=game_setting.level1_required_produce
              p.level = 1
              p.com_produce = 0
            end
          elsif level==1
            if com_produce>=game_setting.level2_required_produce
              p.level = 2
              p.com_produce = 0
            end
          elsif level==2
            if com_produce>=game_setting.level3_required_produce
              p.level = 3
              p.com_produce = 0
            end
          elsif level==3
            if com_produce>game_setting.level4_required_produce
              p.level = 4
              p.com_produce = 0
            end
          else
          end
        else
          p.com_produce = 0
        end
        p.save

        pb.onprocess_inventory_unit = 0
        pb.save
      end
    end

    prices = Price.find(:all, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    prices.each do |p|
      p.destroy
    end

    sales = Sale.find(:all, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    sales.each do |s|
      s.destroy
    end
    render :text=>game.current_year, :layout=>false
  end

  def start_year_a
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    game_setting = game.game_setting
    game.a_run_flag = 'Y'
    game.save

    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, 'A'])
    players.each do |p|
      level = p.level
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
      last_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year-1])
      if pb
        produce = pb.onprocess_inventory_unit
        
        total_rawmat = pb.rawmat_unit
        last_total_rawmat = last_pb.rawmat_unit
        total = total_rawmat - last_total_rawmat

        com_produce = p.com_produce + produce
        cost_d = 0
        if pb.marketing==0
          p.com_produce = com_produce
          if level==0
            if com_produce>=game_setting.level1_required_produce
              p.level = 1
              p.com_produce = 0
              cost_d = game_setting.level1_price_added
            end
          elsif level==1
            if com_produce>=game_setting.level2_required_produce
              p.level = 2
              p.com_produce = 0
              cost_d = game_setting.level2_price_added
            end
          elsif level==2
            if com_produce>=game_setting.level3_required_produce
              p.level = 3
              p.com_produce = 0
              cost_d = game_setting.level3_price_added
            end
          elsif level==3
            if com_produce>game_setting.level4_required_produce
              p.level = 4
              p.com_produce = 0
              cost_d = game_setting.level4_price_added
            end
          else
          end
	  p.save
	  if level==1
            cost_d = game_setting.level1_price_added
          elsif level==2
            cost_d = game_setting.level2_price_added
          elsif level==3
            cost_d = game_setting.level3_price_added
          elsif level==4
            cost_d = game_setting.level4_price_added
          else
          end
        else
          p.com_produce = 0
          if level==1
            cost_d = game_setting.level1_price_added
          elsif level==2
            cost_d = game_setting.level2_price_added
          elsif level==3
            cost_d = game_setting.level3_price_added
          elsif level==4
            cost_d = game_setting.level4_price_added
          else
          end
        end
        ################################################
        pb.rawmat_cost = pb.rawmat_cost - (cost_d*total)
        if pb.rawmat_unit==0
          pb.rawmat_unitcost = 0
        else
          pb.rawmat_unitcost = pb.rawmat_cost.to_f/pb.rawmat_unit
        end
        pb.cash = pb.cash + (cost_d*total)
        pb.save
        ################################################
        p.save

        pb.inventory_unit = pb.inventory_unit + produce
        pb.inventory_cost = ((pb.inventory_cost + (produce * pb.rawmat_unitcost))/10000.0).round * 10000
        if pb.inventory_unit==0
          pb.inventory_unitcost = 0
        else
          pb.inventory_unitcost = pb.inventory_cost.to_f/pb.inventory_unit
        end

        pb.rawmat_unit = pb.rawmat_unit - produce
        pb.rawmat_cost = ((pb.rawmat_unitcost * pb.rawmat_unit)/10000.0).round * 10000

        p.remain_inventory = pb.inventory_unit

        pb.onprocess_inventory_unit = 0
        pb.save
      end
    end
    redirect_to :action=>"gamepanel_a", :gencode=>params[:id]
  end

  def start_year_a_bk
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    game_setting = game.game_setting
    game.a_run_flag = 'Y'
    game.save

    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, 'A'])
    players.each do |p|
      level = p.level
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
      last_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year-1])
      if pb
        produce = pb.onprocess_inventory_unit
        pb.inventory_unit = pb.inventory_unit + produce
        pb.inventory_cost = ((pb.inventory_cost + (produce * pb.rawmat_unitcost))/10000.0).round * 10000
        if pb.inventory_unit==0
          pb.inventory_unitcost = 0
        else
          pb.inventory_unitcost = pb.inventory_cost.to_f/pb.inventory_unit
        end
###################################################
        total_rawmat = pb.rawmat_unit
        last_total_rawmat = last_pb.rawmat_unit
        total = total_rawmat - last_total_rawmat
###################################################

        pb.rawmat_unit = pb.rawmat_unit - produce
        pb.rawmat_cost = ((pb.rawmat_unitcost * pb.rawmat_unit)/10000.0).round * 10000

        p.remain_inventory = pb.inventory_unit
        com_produce = p.com_produce + produce
        if pb.marketing==0
          p.com_produce = com_produce
          cost_d = 0
          if level==0
            if com_produce>=game_setting.level1_required_produce
              p.level = 1
              p.com_produce = 0
              cost_d = 2
            end
          elsif level==1
            if com_produce>=game_setting.level2_required_produce
              p.level = 2
              p.com_produce = 0
              cost_d = 2
            end
          elsif level==2
            if com_produce>=game_setting.level3_required_produce
              p.level = 3
              p.com_produce = 0
              cost_d = 2
            end
          elsif level==3
            if com_produce>game_setting.level4_required_produce
              p.level = 4
              p.com_produce = 0
              cost_d = 4
            end
          else
          end
          ################################################
          pb.rawmat_cost = pb.rawmat_cost - (cost_d*total)
          pb.rawmat_unitcost = pb.rawmat_cost.to_f/pb.rawmat_unit
          pb.cash = pb.cash + (cost_d*total)
          ################################################
        else
          p.com_produce = 0
        end
        p.save

        pb.onprocess_inventory_unit = 0
        pb.save
      end
    end
    redirect_to :action=>"gamepanel_a", :gencode=>params[:id]
  end

  def end_year
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    auto_futures(game.id)

    game_setting = game.game_setting
    game_setting.total_q = 0
    game_setting.total_mul = 0
    game_setting.save

    #### this part is about A/R A/P ####
    accounts = Account.find(:all, :conditions=>["game_id=? AND due_year=?", game.id, game.current_year])
    accounts.each do |acc|
      if acc.debtor_id!=0
        creditor = Player.find(acc.creditor_id)
        debtor = Player.find(acc.debtor_id)
        creditor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", creditor.id, game.current_year])
        debtor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", debtor.id, game.current_year])
        creditor_pb.cash = creditor_pb.cash + acc.amount
        creditor_pb.ar = creditor_pb.ar - acc.amount
        creditor_pb.save
        debtor_pb.cash = debtor_pb.cash - acc.amount
        debtor_pb.ap = debtor_pb.ap - acc.amount
        debtor_pb.save
      else
        creditor = Player.find(acc.creditor_id)
        creditor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", creditor.id, game.current_year])
        creditor_pb.cash = creditor_pb.cash + acc.amount
        creditor_pb.ar = creditor_pb.ar - acc.amount
        creditor_pb.save
      end
    end

    players = Player.find(:all, :conditions=>["game_id=?", game.id])
    players.each do |p|
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
      sold = 0
      sold_unit = 0
      cogs = 0
      if p.player_type=="B"
        sold = Sale.sum(:cash, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
        sold_unit = Sale.sum(:quantity, :conditions=>["player_id=? AND year=?", p.id, game.current_year])
      else
        sold = pb.sold
        sold_unit = pb.sold_unit
      end
      cogs = pb.put_option_cost + ((sold_unit * pb.inventory_unitcost)/10000.0).round * 10000
      remain_inventory = pb.inventory_unit - sold_unit
      waste_cogs = 0.0
      debts = Debt.find(:all, :conditions=>["player_id=?", p.id])
      factories = Factory.find(:all, :conditions=>["player_id=?", p.id])
      warehouses = Warehouse.find(:all, :conditions=>["player_id=?", p.id])
      warehouse_capacity = warehouses.size * game_setting.warehouse_capacity
      if remain_inventory>warehouse_capacity
        waste_cogs += (remain_inventory - warehouse_capacity) * pb.inventory_unitcost
        remain_inventory = warehouse_capacity
      end
      if pb.rawmat_unit>(warehouse_capacity-remain_inventory)
        waste_cogs += (pb.rawmat_unit - (warehouse_capacity-remain_inventory)) * pb.rawmat_unitcost
        pb.rawmat_unit = warehouse_capacity - remain_inventory
      end

      #### this part is about fix loss rate####
      inventory_loss_rate = 0
      rawmat_loss_rate = 0
      if p.player_type=="B"
        inventory_loss_rate = game_setting.inventory_loss_rate
        rawmat_loss_rate = game_setting.rawmat_loss_rate
      else
        inventory_loss_rate = game_setting.inventory_loss_rate_a
        rawmat_loss_rate = game_setting.rawmat_loss_rate_a
      end

      waste_cogs += (((remain_inventory * inventory_loss_rate)/10000.0).to_i * 10000) * pb.inventory_unitcost
      remain_inventory = remain_inventory - (((remain_inventory * inventory_loss_rate)/10000.0).to_i * 10000)
      waste_cogs += (((pb.rawmat_unit * rawmat_loss_rate)/10000.0).to_i * 10000) * pb.rawmat_unitcost
      pb.rawmat_unit = pb.rawmat_unit - (((pb.rawmat_unit * rawmat_loss_rate)/10000.0).to_i * 10000)
      
      waste_cogs = (waste_cogs/10000.0).round * 10000

      marketing = pb.marketing
      depreciation = 0
      factories.each do |f|
        depr = f.price/game_setting.factory_life
        depreciation += depr
        f.remain_value = f.remain_value - depr
        f.save
        if f.remain_value<=0
          f.destroy
        end
      end
      warehouses.each do |w|
        depr = w.price/game_setting.warehouse_life
        depreciation += depr
        w.remain_value = w.remain_value - depr
        w.save
        if w.remain_value<=0
          w.destroy
        end
      end
      debt_interest = 0
      debt_return = 0
      debts.each do |d|
        interest = d.interest
        debt_interest += interest
        if game.current_year==d.end_year
          debt_return += d.amount
          d.destroy
        end
      end
      if game_setting.promotion=='N'
        pb.promotion = 0
        pb.save
      end
      ebt = sold + pb.etc - cogs - waste_cogs + pb.futures_revenue - marketing - pb.promotion - depreciation - debt_interest - pb.emergency_debt_interest
      pretax = ebt * game_setting.tax_rate
      tax = (pretax/10000.0).to_i * 10000
      if tax<0
        tax = 0
      end
      net_income = ebt - tax
      retain_earning = pb.retain_earning + net_income
      equity_per_share = number_with_precision((retain_earning + pb.common_stock.to_f)/pb.common_stock_unit, :precision=>2).to_f
      cash = pb.cash + sold - pb.promotion - debt_interest - debt_return - tax
      if p.player_type=="A"
        cash = cash - sold
      end
      emergency_debt = 0
      if cash<0
        emergency_debt = ((cash*-1)/1000000.0).ceil * 1000000
        cash = cash + emergency_debt
      end

      pb.inventory_unit = remain_inventory
      pb.inventory_cost = ((pb.inventory_unit * pb.inventory_unitcost)/10000.0).round * 10000
      pb.rawmat_cost = ((pb.rawmat_unit * pb.rawmat_unitcost)/10000.0).round * 10000
      pb.sold = sold
      pb.sold_unit = sold_unit
      pb.cogs = cogs
      pb.put_option_cost = 0
      pb.put_option_unit = 0
      pb.waste_cogs = waste_cogs.to_i
      pb.depreciation = depreciation
      pb.debt_interest = debt_interest
      pb.debt_return = debt_return
      pb.emergency_debt = emergency_debt
      pb.cash = cash
      pb.ebt = ebt
      pb.tax = tax
      pb.net_income = net_income
      pb.retain_earning = retain_earning
      pb.equity_per_share = equity_per_share
      pb.save

      ar_value = Account.sum(:amount, :conditions=>["creditor_id=? AND due_year>? AND trade_year<=?", p.id, game.current_year, game.current_year])
      factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", p.id, game.current_year])
      warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", p.id, game.current_year])
      total_assets = pb.cash + pb.futures + ar_value + pb.rawmat_cost + pb.inventory_cost + factories_value + warehouses_value
      debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", p.id, game.current_year])
      total_de = pb.common_stock + pb.retain_earning + debts_value + pb.ap + pb.emergency_debt

      if total_de>total_assets
        pb.inventory_cost = pb.inventory_cost + (total_de-total_assets)
        pb.save
      elsif total_de<total_assets
        pb.inventory_cost = pb.inventory_cost + (total_de-total_assets)
        pb.save
      else
      end
      
      total_assets = pb.cash + pb.futures + ar_value + pb.rawmat_cost + pb.inventory_cost + factories_value + warehouses_value
      pb.total_assets = total_assets
      pb.save

      next_pb = PlayerBalance.new
      next_pb.player_id = p.id
      next_pb.year = game.current_year + 1
      next_pb.cash = pb.cash - emergency_debt - (emergency_debt*game_setting.emergency_debt_rate)
      next_pb.futures = pb.futures
      next_pb.ar = pb.ar
      next_pb.ap = pb.ap
      next_pb.emergency_debt_return = emergency_debt
      next_pb.emergency_debt_interest = emergency_debt*game_setting.emergency_debt_rate
      next_pb.common_stock = pb.common_stock
      next_pb.common_stock_unit = pb.common_stock_unit
      next_pb.inventory_unit = pb.inventory_unit
      next_pb.inventory_cost = pb.inventory_cost
      next_pb.inventory_unitcost = pb.inventory_unitcost
      next_pb.rawmat_unit = pb.rawmat_unit
      next_pb.rawmat_cost = pb.rawmat_cost
      next_pb.rawmat_unitcost = pb.rawmat_unitcost
      next_pb.retain_earning = pb.retain_earning
      next_pb.equity_per_share = pb.equity_per_share
      next_pb.save

      board_data_fill(p.id, game.current_year)
    end

    ge = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    inflation_rate = 1.0 + ge.inflation
    game_setting.unit_cost = (game_setting.unit_cost * inflation_rate).round
    game_setting.rawmat_unit_cost = (game_setting.rawmat_unit_cost * inflation_rate).round
    game_setting.level1_required_marketing = ((game_setting.level1_required_marketing * inflation_rate)/10000.0).round * 10000
    game_setting.level2_required_marketing = ((game_setting.level2_required_marketing * inflation_rate)/10000.0).round * 10000
    game_setting.level3_required_marketing = ((game_setting.level3_required_marketing * inflation_rate)/10000.0).round * 10000
    game_setting.level4_required_marketing = ((game_setting.level4_required_marketing * inflation_rate)/10000.0).round * 10000
    game_setting.factory_price = ((game_setting.factory_price * inflation_rate)/100000.0).round * 100000
    game_setting.warehouse_price = ((game_setting.warehouse_price * inflation_rate)/100000.0).round * 100000

    game_setting.last_price = nil
    game_setting.save

    game.current_year = game.current_year + 1
    game.run_flag = 'N'
    game.a_run_flag = 'N'
    game.current_round = 0
    game.market_remain = -1
    game.save

    render :text=>game.current_year, :layout=>false
  end

  def board_data_fill(player_id, year)
    @player = Player.find(:first, :conditions=>["id=?", player_id])
    @year = year
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    @last_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year-1])
    @pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @debts = Debt.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories = Factory.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses = Warehouse.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories_price =  Factory.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses_price =  Warehouse.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year])

    @pb.total_long_debts = @debts_value
    @pb.total_fixed_assets = @factories_price + @warehouses_price
    @pb.save

    @last_debts_value = @last_pb.total_long_debts
    #@last_factories_price =  Factory.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year-1])
    #@last_warehouses_price =  Warehouse.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year-1])
    @cap_ex = @pb.cap_ex

    board = Board.find(:first, :conditions=>["player_id=? AND year=?", @player.id, year])
    if !board
      board = Board.new
      board.player_id = player_id
      board.year = year
    end
    board.board_data = render_to_string(:action => "show_board", :layout => false)
    board.income_statement = render_to_string(:action => "show_income_statement", :layout => false)
    board.balance_sheet = render_to_string(:action => "show_balance_sheet", :layout => false)
    board.cash_flow_statement = render_to_string(:action => "show_cash_flow_statement", :layout => false)
    board.save
  end

  def test_income_statement
    @player = Player.find(:first, :conditions=>["id=?", params[:player_id]])
    @year = params[:year]
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    @pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @debts = Debt.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories = Factory.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses = Warehouse.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    render :action=>"show_income_statement", :layout => false
  end

  def test_cash_flow_statement
    @player = Player.find(:first, :conditions=>["id=?", params[:player_id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    @last_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year-1])
    @pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @debts = Debt.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories = Factory.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses = Warehouse.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @last_debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year-1])

    @factories_price =  Factory.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses_price =  Warehouse.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @last_factories_price =  Factory.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year-1])
    @last_warehouses_price =  Warehouse.sum(:price, :conditions=>["player_id=? AND year<=?", @player.id, @year-1])
    @cap_ex = @last_factories_price + @last_warehouses_price - @factories_price - @warehouses_price

    render :action=>"show_cash_flow_statement", :layout => false
  end

  def test_balance_sheet
    @player = Player.find(:first, :conditions=>["id=?", params[:player_id]])
    @year = params[:year]
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    @pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @debts = Debt.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories = Factory.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses = Warehouse.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    render :action=>"show_balance_sheet", :layout => false
  end

  def start_round
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game_setting = game.game_setting
    game_setting.step_remain = game_setting.total_step
    game_setting.save
    if !params[:price].empty?
      game.current_round = game.current_round + 1
      game.save
      begin
        game_setting.last_price = params[:price].to_i
        game_setting.save
      rescue
      end
      price = Price.find(:first, :conditions=>["game_id=? AND year=? AND round=?", game.id, game.current_year, game.current_round])
      if !price
        price = Price.new
        price.game_id = game.id
        price.year = game.current_year
        price.round = game.current_round
      end
      begin
        price.price = params[:price].to_i
      rescue
      end
      price.save

      sales = Sale.find(:all, :conditions=>["game_id=? AND year=? AND round=?", game.id, game.current_year, game.current_round])
      sales.each do |s|
        s.destroy
      end

      players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"], :order=>"price, updated_at")
      players.each_with_index do |p,i|
        if p.remain_inventory>0
          sale_order = i+1
          sale = Sale.new
          sale.game_id = game.id
          sale.year = game.current_year
          sale.round = game.current_round
          sale.player_id = p.id
          sale.random_price = params[:price].to_i
          sale.price = p.price
          if p.level==0
            sale.price_added = game_setting.level0_price_added
          elsif p.level==1
            sale.price_added = game_setting.level1_price_added
          elsif p.level==2
            sale.price_added = game_setting.level2_price_added
          elsif p.level==3
            sale.price_added = game_setting.level3_price_added
          else
            sale.price_added = game_setting.level4_price_added
          end
          sale.sale_order = sale_order
          if p.price<=params[:price].to_i
            sale.sale_flag = 'Y'
          end
          sale.save
        end
      end
    end
    render :text=>game.current_round, :layout=>false
  end

  def show_futures_panel
    @game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @game_setting = @game.game_setting
    render :action=>"show_futures_panel", :layout=>false
  end

  def refresh_remain
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    render :text=>number_with_delimiter(game.market_remain), :layout=>false
  end

  def refresh_price
    @game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @price = ''
    p = Price.find(:first, :conditions=>["game_id=? AND year=? AND round=?", @game.id, @game.current_year, @game.current_round])
    if p
      @price = p.price
    end
    render :text=>@price, :layout=>false
  end

  def refresh_random_market
    @gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @min_error = game.min_error
    @max_error = game.max_error
    game_error = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    if game_error
      @min_error = game_error.min_error
      @max_error = game_error.max_error
    end
    render :action=>"refresh_random_market", :layout=>false
  end

  def refresh_random_price
    @gencode = params[:id]
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @min_price = game.min_price
    @max_price = game.max_price
    game_error = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    if game_error
      @min_price = game_error.min_price
      @max_price = game_error.max_price
    end
    render :action=>"refresh_random_price", :layout=>false
  end

  def order_area
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @game_setting = game.game_setting
    @bids = Trade.find(:all, :conditions=>["bidask_flag=? AND game_id=? AND t_status=?", "B", game.id, "Openned"])
    @asks = Trade.find(:all, :conditions=>["bidask_flag=? AND game_id=? AND t_status=?", "A", game.id, "Openned"])
    render :action=>"order_area", :layout=>false
  end

  def chart_data
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"])
    xml = "<chart caption='Market Size(Unit)' numberPrefix=''>"
    xml += "<set label='Remain' value='#{game.market_remain}' />"
    players.each do |p|
      xml += "<set label='#{p.name}' value='#{get_player_sold(game.id, p.id)}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def chart_data_big
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"])
    xml = "<chart caption='Market Size(Unit)' numberPrefix='' baseFontSize='25'>"
    xml += "<set label='Remain' value='#{game.market_remain}' />"
    players.each do |p|
      xml += "<set label='#{p.name}' value='#{get_player_sold(game.id, p.id)}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def zoom_chart_data
    @gencode = params[:id]
    render :action=>"zoom_chart_data", :layout=>false
  end

  def zoom_chart_data_sold
    @gencode = params[:id]
    render :action=>"zoom_chart_data_sold", :layout=>false
  end

  def zoom_chart_data_bought
    @gencode = params[:id]
    render :action=>"zoom_chart_data_bought", :layout=>false
  end

  def chart_data_sold
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "A"])
    xml = "<chart caption='Sold (Unit)' numberPrefix=''>"
    players.each do |p|
      sold = Account.sum(:quantity, :conditions=>["game_id=? AND trade_year=? AND creditor_id=? AND debtor_id!=?", game.id, game.current_year, p.id, 0])
      xml += "<set label='#{p.name}' value='#{sold}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def chart_data_sold_big
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "A"])
    xml = "<chart caption='Sold (Unit)' numberPrefix='' baseFontSize='25'>"
    players.each do |p|
      sold = Account.sum(:quantity, :conditions=>["game_id=? AND trade_year=? AND creditor_id=? AND debtor_id!=?", game.id, game.current_year, p.id, 0])
      xml += "<set label='#{p.name}' value='#{sold}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def chart_data_bought
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"])
    xml = "<chart caption='Bought (Unit)' numberPrefix=''>"
    players.each do |p|
      sold = Account.sum(:quantity, :conditions=>["game_id=? AND trade_year=? AND debtor_id=? AND creditor_id!=?", game.id, game.current_year, p.id, 0])
      xml += "<set label='#{p.name}' value='#{sold}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def chart_data_bought_big
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    players = Player.find(:all, :conditions=>["game_id=? AND player_type=?", game.id, "B"])
    xml = "<chart caption='Bought (Unit)' numberPrefix='' baseFontSize='25'>"
    players.each do |p|
      sold = Account.sum(:quantity, :conditions=>["game_id=? AND trade_year=? AND debtor_id=? AND creditor_id!=?", game.id, game.current_year, p.id, 0])
      xml += "<set label='#{p.name}' value='#{sold}' />"
    end
    xml += "</chart>"
    headers['Content-Type'] = "text/xml"
    render :text=>xml
  end

  def get_player_sold(game_id, player_id)
    game = Game.find(game_id)
    sold = Sale.sum(:quantity, :conditions=>["game_id=? AND player_id=? AND year=? AND round<=?", game.id, player_id, game.current_year, game.current_round])
    return sold
  end

  def refresh_chart
    @gencode = params[:id]
    render :action=>"refresh_chart", :layout=>false
  end

  def refresh_round
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    render :text=>"#{game.current_round}", :layout=>false
  end

  def refresh_result
    @game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    @sales = Sale.find(:all, :conditions=>["game_id=? AND year=? AND round=? AND sale_flag=?", @game.id, @game.current_year, @game.current_round, 'Y'])
    render :action=>"refresh_result", :layout=>false
  end

  def allow_roll
    sale = Sale.find(params[:id])
    sale.sold_flag = 'Y'
    sale.save
  end

  def roll
    @sale = Sale.find(params[:id])
    render :action=>"roll", :layout=>false
  end

  def clear_sale
    sold = 0
    sale = Sale.find(params[:id])
    sold = sale.quantity
    sale.quantity = 0
    sale.cash = 0
    sale.sold_flag = 'N'
    sale.save

    game = Game.find(sale.game_id)
    game.market_remain = game.market_remain + sold
    game.save

    player = Player.find(sale.player_id)
    player.remain_inventory = player.remain_inventory + sold
    player.save
  end

  def setting_parameter
    @word = ''
    if params[:word]
      @word = params[:word]
    end
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @game_setting = GameSetting.find(:first, :conditions=>["game_id=?", @game.id])
    @game_errors = GameError.find(:all, :conditions=>["game_id=?", @game.id])
    render :action=>"setting_parameter", :layout=>"basic_noheader_layout"
  end

  def set_parameter
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game_setting = GameSetting.find(:first, :conditions=>["game_id=?", game.id])
    game_setting.update_attributes(params[:game_setting])
    game_setting.last_price = nil
    game_setting.average_price = nil
    game_setting.total_mul = 0
    game_setting.total_q = 0
    game_setting.save

    do_reset_game(game.id)

    redirect_to :action=>"setting_parameter", :gencode=>params[:gencode], :word=>"Done! #{Time.now}"
  end

  def set_bidask
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game.min_sold = params[:min_sold]
    game.max_sold = params[:max_sold]
    game.save
    game_setting = GameSetting.find(:first, :conditions=>["game_id=?", game.id])
    game_setting.update_attributes(params[:game_setting])
    game_setting.save

    redirect_to :action=>"setting_parameter", :gencode=>params[:gencode], :word=>"Done! #{Time.now}"
  end

  def do_reset_game(game_id)
    game = Game.find(game_id)
    game.current_year = 1
    game.current_round = 0
    game.market_size = game.max_player * 1000000
    game.market_remain = game.max_player * 1000000
    game.run_flag = 'N'
    game.a_run_flag = 'N'
    game.save

    trades = Trade.find(:all, :conditions=>["game_id=?", game_id])
    trades.each do |t|
      t.destroy
    end

    contracts = Contract.find(:all, :conditions=>["game_id=?", game_id])
    contracts.each do |c|
      c.destroy
    end

    accounts = Account.find(:all, :conditions=>["game_id=?", game_id])
    accounts.each do |acc|
      acc.destroy
    end

    game_setting = GameSetting.find(:first, :conditions=>["game_id=?", game_id])
    players = Player.find(:all, :conditions=>["game_id=?", game_id])
    players.each do |p|
      p.remain_inventory = 0
      p.com_produce = 0
      p.price = 999
      p.level = 0
      p.save

      debts = Debt.find(:all, :conditions=>["player_id=?", p.id])
      debts.each do |d|
        d.destroy
      end
      factories = Factory.find(:all, :conditions=>["player_id=?", p.id])
      factories.each do |f|
        f.destroy
      end
      warehouses = Warehouse.find(:all, :conditions=>["player_id=?", p.id])
      warehouses.each do |w|
        w.destroy
      end

      player_balances = PlayerBalance.find(:all, :conditions=>["player_id=?",p.id])
      player_balances.each do |player_balance|
        player_balance.destroy
      end

      pb = PlayerBalance.new
      pb.player_id = p.id
      pb.year = 0
      pb.cash = game_setting.start_cash
      pb.common_stock = game_setting.start_cash
      pb.common_stock_unit = game_setting.start_common_stock_unit
      pb.equity_per_share = game_setting.start_cash/game_setting.start_common_stock_unit
      pb.save

      pb = PlayerBalance.new
      pb.player_id = p.id
      pb.year = 1
      pb.cash = game_setting.start_cash
      pb.common_stock = game_setting.start_cash
      pb.common_stock_unit = game_setting.start_common_stock_unit
      pb.equity_per_share = game_setting.start_cash/game_setting.start_common_stock_unit
      pb.save
    end
    
    prices = Price.find(:all, :conditions=>["game_id=?", game_id])
    prices.each do |price|
      price.destroy
    end

    sales = Sale.find(:all, :conditions=>["game_id=?", game_id])
    sales.each do |s|
      s.destroy
    end
  end

  def set_error
    game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    game_errors = GameError.find(:all, :conditions=>["game_id=?", game.id])
    game_errors.each do |ge|
      ge.min_error = params["min_error_#{ge.year}"]
      ge.max_error = params["max_error_#{ge.year}"]
      ge.min_price = params["min_price_#{ge.year}"]
      ge.max_price = params["max_price_#{ge.year}"]

      ge.put_price_a = params["put_price_a_#{ge.year}"]
      ge.put_exprice_a = params["put_exprice_a_#{ge.year}"]
      ge.put_price_b = params["put_price_b_#{ge.year}"]
      ge.put_exprice_b = params["put_exprice_b_#{ge.year}"]

      ge.inflation = params["inflation_#{ge.year}"]
      ge.save
    end
    redirect_to :action=>"setting_parameter", :gencode=>params[:gencode], :word=>"Done! #{Time.now}"
  end

  def match_order
    game = Game.find(:first, :conditions=>["gencode=?",params[:id]])
    offers = Trade.find(:all, :conditions=>["game_id=? AND t_status=? AND year=? AND bidask_flag=? AND remain_quantity>0", game.id, "Openned", game.current_year, "A"], :order=>"realcost")
    offers.each do |o|
      count = 0
      while o.remain_quantity>0 do
        count += 1
        if count>5
          break
        end
        remain = o.remain_quantity
        well_bids = Trade.find(:all, :conditions=>["game_id=? AND t_status=? AND year=? AND bidask_flag=? AND price>=? AND credit_term<=? AND remain_quantity>0", game.id, "Openned", game.current_year, "B", o.price, o.credit_term], :order=>"remain_quantity")
        if well_bids.size>0
          unit_quota = ((remain.to_f/well_bids.size)/10000).floor * 10000
          if unit_quota<=0
            break;
          end
          well_bids.each_with_index do |wb,i|
            bid_remain = wb.remain_quantity
            sold_unit = 0
            if unit_quota>bid_remain
              sold_unit = bid_remain
              if (well_bids.size - i - 1)>0
                unit_quota = (((o.remain_quantity - sold_unit)/(well_bids.size - i - 1))/10000).floor * 10000
              end
            else
              sold_unit = unit_quota
            end
            wb.fill_quantity = wb.fill_quantity + sold_unit
            wb.remain_quantity = wb.remain_quantity - sold_unit
            wb.save
            o.fill_quantity = o.fill_quantity + sold_unit
            o.remain_quantity = o.remain_quantity - sold_unit
            o.save

            if sold_unit>0
              account = Account.new
              account.game_id = game.id
              account.creditor_id = o.player_id
              account.debtor_id = wb.player_id
              account.price = o.price
              account.credit_term = o.credit_term
              account.quantity = sold_unit
              account.amount = sold_unit * o.price
              account.trade_year = game.current_year
              account.due_year = game.current_year + o.credit_term - 1
              account.save

              #### Add A/R A/P in player balance####
              creditor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", o.player_id, game.current_year])
              creditor_pb.ar = creditor_pb.ar + (sold_unit * o.price)
  #            creditor_pb.inventory_unit = creditor_pb.inventory_unit - sold_unit
  #            creditor_pb.inventory_cost = ((creditor_pb.inventory_unit * creditor_pb.inventory_unitcost)/10000.0).round * 10000
              creditor_pb.sold = creditor_pb.sold + (sold_unit * o.price)
              creditor_pb.sold_unit = creditor_pb.sold_unit + sold_unit
              creditor_pb.save
              debtor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", wb.player_id, game.current_year])
              debtor_pb.ap = debtor_pb.ap + (sold_unit * o.price)
              debtor_pb.rawmat_unit = debtor_pb.rawmat_unit + sold_unit
              debtor_pb.rawmat_cost = debtor_pb.rawmat_cost + (sold_unit * o.price)
              if debtor_pb.rawmat_unit>0
                debtor_pb.rawmat_unitcost = debtor_pb.rawmat_cost.to_f/debtor_pb.rawmat_unit
              else
                debtor_pb.rawmat_unitcost = 0
              end
              debtor_pb.save
            end
          end
        else
          break
        end
      end
    end
    trades = Trade.find(:all, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
    trades.each do |t|
      t.destroy
    end
    redirect_to :action=>"gamepanel_a", :gencode=>params[:id]
  end

  def trophy
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy", :layout=>"basic_noheader_layout"
  end

  def trophy_profit
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_profit", :layout=>"basic_noheader_layout"
  end

  def trophy_thrift
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_thrift", :layout=>"basic_noheader_layout"
  end

  def trophy_selling
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_selling", :layout=>"basic_noheader_layout"
  end

  def trophy_margin
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_margin", :layout=>"basic_noheader_layout"
  end

  def trophy_inventory_planner
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_inventory_planner", :layout=>"basic_noheader_layout"
  end

  def trophy_roa
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_roa", :layout=>"basic_noheader_layout"
  end

  def trophy_roe
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_roe", :layout=>"basic_noheader_layout"
  end

  def trophy_cashflow
    @gencode = params[:gencode]
    @game = Game.find(:first, :conditions=>["gencode=?",params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?",@game.id])
    render :action=>"trophy_cashflow", :layout=>"basic_noheader_layout"
  end

  def print_all_player
    game = Game.find(:first, :conditions=>["gencode=?", params[:gencode]])
    @players = Player.find(:all, :conditions=>["game_id=?", game.id])
    @year = params[:year].to_i
    @game_setting = game.game_setting
    render :action=>"print_all_player", :layout=>"basic_noheader_layout"
  end

  def a_check
    game = Game.find(:first, :conditions=>["gencode=?", params[:id]])
    @players = Player.find(:all, :conditions=>["game_id=? AND player_type='A'", game.id])
    render :action=>"a_check", :layout=>"basic_noheader_layout"
  end

  def b_check
    game = Game.find(:first, :conditions=>["gencode=?", params[:id]])
    @players = Player.find(:all, :conditions=>["game_id=? AND player_type='B'", game.id])
    render :action=>"b_check", :layout=>"basic_noheader_layout"
  end

  def offer_area
    @player = Player.find(params[:id])
    @game = Game.find(@player.game_id)
    render :action=>"offer_area", :layout=>false
  end

end
